package p.ithorns.sample.office.excel;

import cn.idev.excel.EasyExcel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import p.ithorns.framework.common.utils.JsonUtil;

import java.io.InputStream;
import java.util.*;

/**
 * ComplexExcelService
 *
 * @author HtL
 * @date 2024/8/28 16:07
 * @since 1.0.0
 */
@Slf4j
@Service
public class ComplexExcelService {

    /**
     * 导入
     */
    public void doImport(MultipartFile file) {
        final MultiHeaderResolver handler = new MultiHeaderResolver();
        try (InputStream inputStream = file.getInputStream()) {
            EasyExcel.read(inputStream, handler)
                    .sheet()
                    .headRowNumber(4)
                    .doRead();
        } catch (Exception e) {
            log.error("解析数据失败", e);
            throw new RuntimeException(e);
        }

        // 导出
        List<HeaderNode> headerNodes = handler.getHeaderNodes();
        System.out.println(JsonUtil.toJson(headerNodes));
        System.out.println("----------------------------------------------------");

        doExport(headerNodes, Collections.emptyList());
    }

    /**
     * 导出
     */
    private void doExport(List<HeaderNode> headerNodes, Collection<?> data) {
        // 构建多头
        List<List<String>> headerNames = MultiHeaderBuilder.build(headerNodes);
        System.out.println(headerNames);

        EasyExcel.write("C:\\Users\\HtL\\Desktop\\复杂表头模版.xlsx")
                // 这里放入动态头
                .head(headerNames)
                .sheet("模板")
                // 当然这里数据也可以用 List<List<String>> 去传入
                .doWrite(data);
    }

}